﻿CREATE TRIGGER [tru_LoanInfo_BuyersOrder]
ON [dbo].[t_LoanInfo]
FOR UPDATE
AS
IF @@ROWCOUNT = 0 RETURN
IF TRIGGER_NESTLEVEL(@@PROCID) > 1 RETURN

IF (UPDATE (SalesTaxAmount) OR UPDATE(UnPaidBalanceWithTax))
BEGIN
	UPDATE LI SET SalesTaxPercent = Tax.SalesTax
	FROM v_BuyersOrder#Update LI
	INNER JOIN inserted i ON i.LoanID = LI.LoanID
	OUTER APPLY Tax(LI.SalesPrice,i.SalesTaxAmount,i.UnPaidBalanceWithTax)Tax

	UPDATE LI SET UnPaidBalanceWithTax = NULL,SalesTaxAmount = NULL
	FROM v_BuyersOrder#Update LI
	INNER JOIN inserted i ON i.LoanID = LI.LoanID
	WHERE LI.SalesPrice <> 0

	UPDATE LI SET SalesPrice = i.UnPaidBalanceWithTax - i.SalesTaxAmount
	FROM v_BuyersOrder#Update LI INNER JOIN inserted i ON i.LoanID = LI.LoanID
	WHERE i.UnPaidBalanceWithTax <> 0 AND i.SalesTaxAmount <> 0
END

IF UPDATE (SalesTaxPercent) AND
	 EXISTS(SELECT * FROM inserted WHERE SalesTaxPercent <> 0)
	UPDATE LI SET UnPaidBalanceWithTax = NULL,
								SalesTaxAmount = NULL
	FROM t_LoanInfo LI INNER JOIN inserted i ON i.LoanID = LI.LoanID
